import Cookies from 'js-cookie'
import { Module } from 'vuex'
import RootStateTypes from "@/store/interface"
import UserModuleTypes from "@/store/modules/user/interface"
import { api } from '@/api/api'

const state = {
  token: Cookies.get('token'),
  name: '',
  mobile: '',
}

const mutations = {
  SET_TOKEN: (state:any, token:UserModuleTypes) => {
    state.token = token
  },
  SET_NAME: (state:any, name:UserModuleTypes) => {
    state.name = name
  },
  SET_MOBILE: (state:any, mobile:UserModuleTypes) => {
    state.mobile = mobile
  }
}

const actions = {
  /**
   * @name 用户登录
   * */
  login({ commit }:any, userInfo:any) {
    const { username, password } = userInfo
    return new Promise<void>((resolve, reject) => {
      api.user.login({
        username: username.trim(),
        password: password
      }).then((response:any) => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        Cookies.set('token', data.token)
        Cookies.set("user_id",data.user.id);
        Cookies.set("username", data.user.name);
        Cookies.set("is_has_child",data.user.is_has_child);
        commit('SET_IS_HAS_CHILD', data.user.is_has_child)
        resolve()
      }).catch((error:any) => {
        reject(error)
      })
    })
  },
}
const userModule:Module<UserModuleTypes, RootStateTypes> = {
  namespaced:true,
  state,
  mutations,
  actions
}
export default userModule
